<template>
  <div class="settings-view">
    <div class="settings-container">
      <h2>应用设置</h2>

      <!-- Interface Settings Card -->
      <el-card class="settings-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>界面设置</span>
          </div>
        </template>
        <el-form label-position="top">
          <el-form-item label="界面主题">
            <div ref="darkModeSwitchContainerRef">
              <el-switch
                  v-model="darkMode"
                  active-text="暗黑模式"
                  inactive-text="浅色模式"
                  @change="handleDarkModeChange"
              />
            </div>
          </el-form-item>

          <el-form-item label="主题色">
            <div class="color-picker-wrapper">
              <el-color-picker
                v-model="themeColor"
                show-alpha
                :predefine="predefineColors"
                @change="updateThemeColor"
              />
              <el-button
                type="primary"
                link
                class="reset-button"
                @click="resetThemeColor"
              >
                重置为默认 ({{ defaultThemeColor }})
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- Layout Settings Card -->
      <el-card class="settings-card" shadow="never">
         <template #header>
          <div class="card-header">
            <span>布局设置</span>
          </div>
        </template>
         <el-form label-position="top">
          <el-form-item label="流程图布局">
            <el-radio-group v-model="layoutDirection" @change="updateDagreDirection">
              <el-radio-button value="TB">水平布局</el-radio-button>
              <el-radio-button value="LR">垂直布局</el-radio-button>
            </el-radio-group>
          </el-form-item>
           <el-form-item label="节点间距">
             <el-input-number
                 v-model="nodesep"
                 :min="30"
                 :max="150"
                 :step="10"
                 controls-position="right"
                 @change="updateNodeSep"
             />
           </el-form-item>
           <el-form-item label="层级间距">
             <el-input-number
                 v-model="ranksep"
                 :min="30"
                 :max="200"
                 :step="10"
                 controls-position="right"
                 @change="updateRankSep"
             />
           </el-form-item>
         </el-form>
      </el-card>

       <!-- Editor & Parsing Settings Card -->
      <el-card class="settings-card" shadow="never">
         <template #header>
          <div class="card-header">
            <span>编辑与解析</span>
          </div>
        </template>
         <el-form label-position="top">
           <el-form-item label="自动刷新可视化">
             <el-switch v-model="autoRefresh" />
           </el-form-item>
            <el-form-item>
              <template #label>
                <span class="form-item-label-with-icon">
                  XML 验证库
                  <el-tooltip placement="top" content="libxml2 提供更严格的验证，但可能略慢且需要现代浏览器支持 WASM。Fast XML Parser 更快，适用于基础语法检查。">
                     <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                </span>
              </template>
              <el-radio-group v-model="selectedValidator" @change="updateSelectedValidator">
                <el-radio value="fast-xml-parser">Fast XML Parser</el-radio>
                <el-radio value="libxml2-wasm">libxml2 (WASM)</el-radio>
              </el-radio-group>
           </el-form-item>
            <el-form-item>
              <template #label>
                <span class="form-item-label-with-icon">
                   XML 解析器
                   <el-tooltip placement="top">
                     <template #content>
                        DOMParser: 浏览器原生，无需额外依赖，适合多数情况。<br/>
                        Fast XML Parser: Javascript 实现，通常更快，错误提示更友好。<br/>
                        libxml2 (WASM): C 库编译，性能潜力最高，功能最全（如XPath），但体积较大且可能需要初始化。
                     </template>
                     <el-icon><QuestionFilled /></el-icon>
                   </el-tooltip>
                 </span>
              </template>
              <el-radio-group v-model="selectedParser" @change="handleParserChange">
                <el-radio value="dom">DOMParser (浏览器内置)</el-radio>
                <el-radio value="fast-xml">Fast XML Parser</el-radio>
                <el-radio value="libxml2">libxml2 (WASM)</el-radio>
              </el-radio-group>
           </el-form-item>
         </el-form>
      </el-card>

       <!-- Formatting Settings Card -->
      <el-card class="settings-card" shadow="never">
         <template #header>
          <div class="card-header">
            <span>XML 格式化</span>
          </div>
        </template>
         <el-form label-position="top">
           <el-form-item label="缩进方式">
              <el-select v-model="formattingIndent" placeholder="选择缩进" @change="updateFormattingIndentation">
                 <el-option label="2 个空格" value="  " />
                 <el-option label="4 个空格" value="    " />
                 <el-option label="Tab (\t)" value="\t" />
               </el-select>
           </el-form-item>
            <el-form-item>
              <template #label>
                 <span class="form-item-label-with-icon">
                   折叠内容
                   <el-tooltip content="是否将空标签折叠为自闭合标签，例如 <tag></tag> 变为 <tag/>" placement="top">
                      <el-icon><QuestionFilled /></el-icon>
                   </el-tooltip>
                 </span>
              </template>
              <el-switch 
                 v-model="formattingCollapse" 
                 @change="updateFormattingCollapse"
                 active-text="是" 
                 inactive-text="否"
               />
           </el-form-item>
            <el-form-item>
              <template #label>
                 <span class="form-item-label-with-icon">
                   换行符
                    <el-tooltip content="LF: Unix/Linux/macOS; CRLF: Windows; CR: Classic Mac OS" placement="top">
                      <el-icon><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </span>
              </template>
               <el-select v-model="formattingSeparator" placeholder="选择换行符" @change="updateFormattingSeparator">
                 <el-option label="LF (\n) - Unix/macOS" value="\n" />
                 <el-option label="CRLF (\r\n) - Windows" value="\r\n" />
                 <el-option label="CR (\r) - Classic Mac" value="\r" />
               </el-select>
           </el-form-item>
         </el-form>
      </el-card>

      <!-- Add Remember Last Folder Toggle Card -->
      <el-card class="settings-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>文件管理器</span>
          </div>
        </template>
        <el-form label-position="top">
          <el-form-item label="记住上次位置">
            <el-switch v-model="rememberLastFolderModel" />
            <el-tooltip content="启用后，刷新页面或重新打开应用时将自动导航到上次离开的文件夹。" placement="top">
               <el-icon style="margin-left: 4px; cursor: help;"><InfoFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- Add Recursive Delete Confirmation Toggle -->
      <el-card class="settings-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>递归删除确认</span>
          </div>
        </template>
        <el-form label-position="top">
          <el-form-item label="递归删除确认">
            <el-switch v-model="settingsStore.confirmRecursiveDelete" />
            <el-tooltip content="启用后，删除非空文件夹时将需要二次确认。" placement="top">
               <el-icon style="margin-left: 4px; cursor: help;"><InfoFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- Visualizer Node Settings Card -->
      <el-card class="settings-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>可视化节点设置</span>
          </div>
        </template>
        <el-form label-position="top">
          <!-- Existing Attribute Display Mode -->
          <el-form-item>
            <template #label>
              <span class="form-item-label-with-icon">
                属性显示模式
                <el-tooltip placement="top">
                  <template #content>
                    隐藏: 不显示任何属性信息。<br />
                    计数: 仅显示属性总数 (Attrs: N)。<br />
                    列表: 显示属性键值对列表（根据下方设置限制数量）。
                  </template>
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </span>
            </template>
            <el-radio-group v-model="visualizerSettings.attributeDisplayMode">
              <el-radio-button value="hide">隐藏</el-radio-button>
              <el-radio-button value="count">计数</el-radio-button>
              <el-radio-button value="first-1">列表(1)</el-radio-button>
              <el-radio-button value="first-3">列表(3)</el-radio-button>
              <el-radio-button value="all">列表(全部)</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!-- Existing Normalize Appearance -->
          <el-form-item>
             <template #label>
               <span class="form-item-label-with-icon">
                 统一节点外观 (基于属性)
                 <el-tooltip content="启用后，即使节点没有属性或属性被隐藏，也会尝试保持与其他节点相似的高度，使布局更整齐。" placement="top">
                   <el-icon><QuestionFilled /></el-icon>
                 </el-tooltip>
               </span>
             </template>
             <el-switch v-model="visualizerSettings.normalizeAppearanceWithAttrs" />
           </el-form-item>

           <!-- Existing Node Coloring Mode -->
           <el-form-item label="节点着色模式">
              <el-radio-group v-model="visualizerSettings.nodeColoringMode">
                <el-radio-button value="semantic">按语义</el-radio-button>
                <el-radio-button value="level">按层级</el-radio-button>
                <el-radio-button value="jdf">按JDF核心标签</el-radio-button>
              </el-radio-group>
           </el-form-item>

           <!-- NEW: Node Rendering Method -->
           <el-form-item>
             <template #label>
               <span class="form-item-label-with-icon">
                 节点渲染方式
                 <el-tooltip placement="top">
                   <template #content>
                     模板: 使用 Vue 模板语法渲染，通常更易读写。<br />
                     Render 函数: 使用 JavaScript (h函数) 渲染，提供更精细的编程控制，可能性能更好。
                   </template>
                   <el-icon><QuestionFilled /></el-icon>
                 </el-tooltip>
               </span>
             </template>
             <el-radio-group v-model="visualizerSettings.nodeRenderingMethod">
               <el-radio-button value="template">模板</el-radio-button>
               <el-radio-button value="renderFunction">Render 函数</el-radio-button>
             </el-radio-group>
           </el-form-item>

        </el-form>
      </el-card>

      <div class="about-section">
        <h3>关于JDFSight</h3>
        <p>版本: 1.0.0</p>
        <p>JDFSight是一款高效的JDF结构可视化和编辑工具，基于Vue 3、TypeScript和VueFlow构建。</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { InfoFilled, QuestionFilled } from '@element-plus/icons-vue'
import { useSettingsStore } from '@/stores/settingsStore'
import { useUniversalVisualizerSettingsStore } from '@/stores/universalVisualizerSettingsStore'

const settingsStore = useSettingsStore()
const visualizerSettings = useUniversalVisualizerSettingsStore()

// 定义默认主题色
const defaultThemeColor = '#409EFF'

const darkMode = ref(settingsStore.darkMode)
const themeColor = ref(settingsStore.themeColor)
const layoutDirection = ref(settingsStore.dagre.rankdir)
const autoRefresh = ref(settingsStore.autoRefresh)
const nodesep = ref(settingsStore.dagre.nodesep)
const ranksep = ref(settingsStore.dagre.ranksep)
// Add ref for validator choice
const selectedValidator = ref<'fast-xml-parser' | 'libxml2-wasm' | 'none'>(settingsStore.selectedXmlValidator)
// Add ref for parser choice
const selectedParser = ref<'dom' | 'fast-xml' | 'libxml2-wasm'>(settingsStore.selectedParser)

// Add refs for formatting options
const formattingIndent = ref(settingsStore.formattingOptions.indentation)
const formattingCollapse = ref(settingsStore.formattingOptions.collapseContent)
const formattingSeparator = ref(settingsStore.formattingOptions.lineSeparator)

// Add ref for remember last folder setting
const rememberLastFolderModel = ref(settingsStore.rememberLastFolder);

// Ref for the dark mode switch container
const darkModeSwitchContainerRef = ref<HTMLDivElement | null>(null)

// 扩展预定义颜色数组 (示例，可以替换为你喜欢的颜色)
const predefineColors = ref([
  '#409EFF', // Default Blue
  '#67C23A', // Success Green
  '#E6A23C', // Warning Orange
  '#F56C6C', // Danger Red
  '#909399', // Info Gray
  '#303133', // Primary Text
  '#ff4500', // OrangeRed
  '#ff8c00', // DarkOrange
  '#ffd700', // Gold
  '#90ee90', // LightGreen
  '#00ced1', // DarkTurquoise
  '#1e90ff', // DodgerBlue
  '#c71585', // MediumVioletRed
  '#7B68EE', // MediumSlateBlue
  '#00FA9A', // MediumSpringGreen
  '#DA70D6', // Orchid
])

// 修改后的切换函数
const handleDarkModeChange = () => {
  if (darkModeSwitchContainerRef.value) {
    const rect = darkModeSwitchContainerRef.value.getBoundingClientRect()
    const x = rect.left + rect.width / 2
    const y = rect.top + rect.height / 2
    settingsStore.toggleDarkModeWithAnimation(x, y)
  } else {
    console.warn('Dark mode switch ref not found, falling back to simple toggle.')
    settingsStore.toggleDarkMode()
  }
}

const updateThemeColor = (color: string | null) => {
  if (color) {
    settingsStore.setThemeColor(color)
  }
}

// 修改重置方法以添加确认和消息提示
const resetThemeColor = () => {
  ElMessageBox.confirm(
    '确定要将主题色重置为默认颜色吗？',
    '重置确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户确认后执行重置
      updateThemeColor(defaultThemeColor)
      // 更新本地 ref，以便选择器立即反映变化
      themeColor.value = defaultThemeColor
      // 显示成功消息
      ElMessage.success('主题色已重置为默认')
    })
    .catch(() => {
      // 用户取消
      // 显示取消消息
      ElMessage.info('已取消重置')
    })
}

const updateDagreDirection = (direction: 'TB' | 'LR') => {
  settingsStore.setDagreDirection(direction)
}

// Add function to update validator choice
const updateSelectedValidator = (validator: 'fast-xml-parser' | 'libxml2-wasm' | 'none') => {
  settingsStore.setSelectedXmlValidator(validator);
};

// Handler for parser change
const handleParserChange = async (parser: 'dom' | 'fast-xml' | 'libxml2-wasm') => {
    settingsStore.setSelectedParser(parser);
    // Optionally trigger re-parse immediately
    ElMessage.info(`解析器已切换为 ${parser}. 下次加载或应用时生效。`);
    // Or: Trigger immediate re-parse (might be slow)
    // const jdfStore = useJDFStore();
    // if (jdfStore.rawContent) {
    //    await jdfStore.parseAndLayoutContent(jdfStore.rawContent);
    //    ElMessage.success('已使用新解析器重新解析当前文档。');
    // }
}

const updateNodeSep = (value: number) => {
  settingsStore.dagre.nodesep = value
}

const updateRankSep = (value: number) => {
  settingsStore.dagre.ranksep = value
}

// Add functions to update formatting options
const updateFormattingIndentation = (value: string) => {
  settingsStore.setFormattingIndentation(value);
}
const updateFormattingCollapse = (value: boolean) => {
  settingsStore.setFormattingCollapseContent(value);
}
// Correct the parameter type to use single backslash, matching the store
const updateFormattingSeparator = (value: '\n' | '\r\n' | '\r') => {
  settingsStore.setFormattingLineSeparator(value);
}

// Add onMounted with log
onMounted(() => {
  console.log('[SettingsView] Component mounted.');
  // Keep existing initialization logic
  darkMode.value = settingsStore.darkMode
  themeColor.value = settingsStore.themeColor
  layoutDirection.value = settingsStore.dagre.rankdir
  autoRefresh.value = settingsStore.autoRefresh
  nodesep.value = settingsStore.dagre.nodesep
  ranksep.value = settingsStore.dagre.ranksep
  selectedValidator.value = settingsStore.selectedXmlValidator
  selectedParser.value = settingsStore.selectedParser
  formattingIndent.value = settingsStore.formattingOptions.indentation
  formattingCollapse.value = settingsStore.formattingOptions.collapseContent
  formattingSeparator.value = settingsStore.formattingOptions.lineSeparator
})

// 监听设置变化 (autoRefresh)
watch(() => settingsStore.autoRefresh, (value) => {
  autoRefresh.value = value
})

// 监听主题色变化，确保 color picker 同步
watch(() => settingsStore.themeColor, (value) => {
  themeColor.value = value
})

// 监听 darkMode 变化，确保 switch 同步 (如果 store 在别处被修改)
watch(() => settingsStore.darkMode, (value) => {
  darkMode.value = value
})

// Watch for external changes to validator setting
watch(() => settingsStore.selectedXmlValidator, (value) => {
  selectedValidator.value = value;
});

// Watch for external changes to parser setting
watch(() => settingsStore.selectedParser, (value) => {
  selectedParser.value = value;
});

// Add watcher for remember last folder setting
watch(rememberLastFolderModel, (newValue) => {
    // Optional: Add immediate feedback or confirmation if needed
    settingsStore.rememberLastFolder = newValue; 
    // console.log('[SettingsView Watch] Remember Last Folder changed to:', newValue);
});

// Watch for external changes to remember last folder setting (e.g., if changed elsewhere)
watch(() => settingsStore.rememberLastFolder, (value) => {
  rememberLastFolderModel.value = value;
});
</script>

<style lang="scss" scoped>
.settings-view {
  padding: 20px;
  // 添加 transition 以实现背景和文字颜色平滑过渡
  transition: background-color 0.3s ease, color 0.3s ease;
  // Force height and overflow to handle scrolling within the view itself
  height: 100%; 
  overflow-y: auto; // Allow vertical scrolling
  box-sizing: border-box; // Include padding in the height calculation

  .settings-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: var(--el-bg-color-overlay);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    // 添加 transition 以实现背景、文字和阴影的平滑过渡
    transition: background-color 0.3s ease, color 0.3s ease, box-shadow 0.3s ease;

    h2 {
      margin-bottom: 20px;
    }

    // Add style for the cards
    .settings-card {
        margin-bottom: 20px; // Add space between cards
        border: none; // Remove card border if shadow="never"
        background-color: transparent; // Inherit background if needed or set specific

        // Style for card header
        .card-header {
            font-weight: bold;
        }
        // Optional: Remove card body padding if form items have enough
        // :deep(.el-card__body) {
        //    padding: 0px 20px 20px 20px;
        // }
    }

    .about-section {
      margin-top: 20px;

      h3 {
        margin-bottom: 10px;
      }

      p {
        color: var(--el-text-color-secondary);
        margin-bottom: 10px;
        // 也为段落文字颜色添加过渡
        transition: color 0.3s ease;
      }
    }
  }
}

// 新增样式用于布局
.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 10px; // 控制选择器和按钮间距
}

.reset-button {
  margin-left: auto; // 可选：如果希望按钮靠右
}

// Style for aligning icon next to label text
.form-item-label-with-icon {
  display: inline-flex; // Use inline-flex to keep it in flow but allow flex alignment
  align-items: center; // Vertically center the icon with the text
  gap: 4px; // Add a small gap between text and icon

  .el-icon {
    color: var(--el-text-color-secondary); // Keep the icon color consistent
    cursor: help; // Indicate it provides help
  }
}
</style>